package cn.jdy.plugins.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.plugins.entity.Doc;
import cn.jdy.plugins.entity.Info;
import cn.jdy.plugins.service.DocService;
import cn.jdy.plugins.service.DownloadService;
import cn.jdy.plugins.service.InfoService;

/**
 * 营销中心控制类
 * Created by Tianyi on 2014/7/10.
 */
@Controller
@RequestMapping("/doc")
public class DocCtrl extends BaseCtrl {

	@Autowired
	private DocService docService;
	@Autowired
	private DownloadService downloadService;
	@Autowired
	private InfoService infoService;
	//默认列表路径
	private static String viewName = "redirect:/doc/list?s=";

	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(Doc entity, String fromDate, String toDate, @RequestParam(required = false) Integer s) {
		ModelAndView mv = new ModelAndView("/operate/docList.jsp");
		if(s!=null)
			switch(s) {
				case 1: mv.addObject("msg", "保存成功！");break;
				case 2: mv.addObject("msg", "更新成功！");break;
				case 3: mv.addObject("msg", "删除成功！");break;
				case 4: mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("classList", confService.queryByType(GlobalConstant.TYPE_DOC, null));
		return mv;
	}

	/**
	 * 异步查询
	 * @param entity
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Doc entity, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", docService.query(entity, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", docService.count(entity, fromDate, toDate));
			jsonMap.put("iTotalRecords", docService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询智库异常", e);
		}
		return jsonMap;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/docDetail.jsp");
		if(id!=null) mv.addObject("entity", this.docService.find(id));
		mv.addObject("bizClass", this.confService.queryByType(GlobalConstant.TYPE_DOC, null));
		return mv;
	}

	/**
	 * 保存（更新）智库
	 * @param entity
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(Doc entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if(entity.getId()==null) {
				User user = getUser();
				entity.setUserId(user.getId());
				entity.setUserName(user.getUsername());
				entity.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.docService.save(entity);
			} else {
				this.docService.updateWithValidator(entity);
			}
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "保存智库异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 执行简单操作（审核等）
	 * @param entity
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Map<String, Object> update(Doc entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			this.docService.update(entity.getId(), "status", entity.getStatus());
			entity.setPostil(request.getParameter("postil"));
			this.docService.update(entity.getId(), "postil", entity.getPostil());
			if("2".equals(entity.getStatus())) {
				entity = this.docService.find(entity.getId());
				ConfValue confValue = confService.find(GlobalConstant.MSG_DOC_UNPASS);
				Info info = new Info();
				info.setType("1");
				info.setTitle(confValue.getRemark().replace("%t", entity.getTitle()));
				info.setContext(confValue.getValue0().replaceFirst("%t", entity.getTitle()).replaceFirst("%r", entity.getPostil()));
				info.setUserid(entity.getUserId());
				infoService.saveOrUpd(info);
			}
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "文章更新异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 删除智库
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.downloadService.delete("docId", id);
			this.docService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除智库异常！", e);
		}
		return mv;
	}

	/**
	 * 下载
	 * @param id
	 * @param response
	 */
	@RequestMapping("/down/{id}")
	@ResponseBody
	public void down(@PathVariable Long id, HttpServletResponse response) {
		Doc doc = docService.find(id);
		if(doc == null) return;
		String fileUrl = doc.getFileUrl();
		if(fileUrl == null || fileUrl.isEmpty()) return;
		File file = new File(GlobalConstant.PROJECT_UPLOAD_PATH + fileUrl);
		if(!file.exists()) {
			BaseLog.e(this.getClass(), "找不到文件:" + file);
			return;
		}
		OutputStream out = null;
		InputStream inStream = null;
		try {
			//准备下载文件
			response.reset();
			request.setCharacterEncoding("UTF-8");
			int extension = fileUrl.lastIndexOf(".");
			String name = doc.getTitle() + (extension>-1?fileUrl.substring(extension):"");
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
			int i = -1;
			inStream = new FileInputStream(file);
			out = response.getOutputStream();
			while((i = inStream.read()) != -1) {
				out.write(i);
			}
			out.flush();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "down:输出流输出时错误!", e);
		} finally {
			try {
				inStream.close();
				out.close();
			} catch(IOException e) {
				BaseLog.e(this.getClass(), "关闭流时出错", e);
			}
		}
	}

}
